package com.yfbao.horizon.encrypt.utils;


import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class MD5Utils {
    private static MessageDigest md = null;
    private static ReentrantLock opLock = new ReentrantLock();

    static {
        synchronized (MD5Utils.class) {
            if (md == null) {
                synchronized (MD5Utils.class) {
                    try {
                        md = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException e) {
                        log.error("init md digest error", e);
                    }
                }
            }
        }
    }

    /**
     * 提供32位md5加密
     *
     * @param src 明文
     * @return
     */
    public static String md5(String src) {
        return md5(src, 32);
    }

    /**
     * 提供16位和32位md5加密
     *
     * @param src    明文
     * @param length 加密长度 16或32位加密
     * @return
     */
    public static String md5(String src, int length) {
        opLock.lock();
        try {
            String returnValue = "";
            String outStr = Hex.toHexString(md.digest(src.getBytes("UTF-8")));
            switch (length) {
                case 16:
                    returnValue = outStr.substring(8, 24);
                    break;
                default:
                    returnValue = outStr;
                    break;
            }
            return returnValue;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            opLock.unlock();
        }
    }
}
